package com.zzzyh.forumsystemclient.cotroller;

import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.ForgotForm;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.services.impl.VerificationCodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Slf4j
public class RegisterController {
    @Autowired
    private IUserService userService;
    @Autowired
    private VerificationCodeServiceImpl verificationCodeService;

    @Autowired
    private PasswordEncoder passwordEncoder; // 注入密码编码器

    @RequestMapping("/email/register")
    public AppResult<String> emailRegister(@RequestBody User  user) {
        log.info("用户注册信息为：{}", user);
        if(!verificationCodeService.validateCode(user.getEmail(), user.getCode())){
            return AppResult.failed("验证码错误");
        }
        // 对密码进行加密
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
        userService.register(user);
        return AppResult.success("注册成功");
    }

    @RequestMapping("/email/forgot")
    public AppResult<String> emailForgot(@RequestBody ForgotForm forgotForm) {
        log.info("用户找回密码信息为：{}", forgotForm);
        if(!verificationCodeService.validateCode(forgotForm.getEmail(), forgotForm.getCode())){
            return AppResult.failed("验证码错误");
        }
        if(!userService.usernameAndEmailExists(forgotForm.getUsername(), forgotForm.getEmail())){
            return AppResult.failed("用户名或邮箱错误");
        }
        Integer userId = userService.selectUserIdByUsername(forgotForm.getUsername());
        userService.updatePassword(passwordEncoder.encode(forgotForm.getPassword()), userId);
        return AppResult.success("找回密码成功");
    }
}
